rm(list= ls())

library(kableExtra)
library(tidyverse)

## Function to summarize variable 

summarize_vec <- function(vector){
  
  mean_v <- mean(vector, na.rm = T)
  median_v <- median(vector, na.rm = T)
  sd_v <- sd(vector, na.rm = T)
  n_obs <- length(vector[!is.na(vector)])
  min_v <- min(vector, na.rm = T)
  max_v <- max(vector, na.rm = T)
  
  
  data.frame(cbind(mean_v, median_v, sd_v, n_obs, min_v, max_v))
  
}

## Load Election Data

dat <- readRDS('data/fed_elections_kreise.rds') %>%
  filter(year >= 1953) %>% 
  filter(year <= 1965) %>%
  filter(type == 'Stadtkreis')  

## Define variables to summarize 

sumvars <- c('cdu_csu', 'spd', 'far_right_vs_excl_dp', 'fdp', 'n_syn_bin')

## Summarize 

dat <- dat %>% 
  dplyr::select(one_of(sumvars)) %>%
  mutate_all(as.numeric) 


summary_all <- apply(dat, 2, summarize_vec) %>%
  reduce(rbind) %>%
  mutate_all(round, 2) %>%
  mutate(label = c('CDU/CSU vote share (in %)', 
                   'SPD vote share (in %)', 
                   'Far-right vote share (NPD/DRP, in %)',
                   'FDP vote share (in %)',
                   'Jewish presence (0/1)')) %>%
  dplyr::select(label, everything())

##

names(summary_all) <- c('Variable', 'Mean', 'Median', 'S.D.', 'N', 'Min', 'Max')

# To Tex Table 

tab_tex <- summary_all %>%
  kableExtra::kable(., format = 'latex', 
                    booktabs = T,
                    linesep = "",
                    label = 'sumstat_voting',
                    caption = 'Summary statistics',
                    digits = 2) %>%
  footnote(footnote_as_chunk = T, threeparttable = T,
           general = "The table shows summary statistics for the county-level voting data, pooled across the federal elections 1953, 1957, 1961, and 1965.") %>%
  kable_styling(latex_options = c("HOLD_position"), 
                position = "center",
                full_width = F,
                font_size = 11) 
tab_tex

